<template>
  <div class="login__container">
    <video
      src="../video/bg_video.d2d602a9.mp4"
      muted="muted"
      autoplay="autoplay"
      loop="loop"
      preload="auto"
      class="bg_video"
    ></video>
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="login_form"
    >
      <h1>万锋管理系统</h1>
      <!--prop校验必要属性 要和rules中的字段进行校验 -->
      <el-form-item label="用户名" prop="username">
        <el-input
          type="text"
          v-model="loginForm.username"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="loginForm.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <!-- 验证码 -->
      <el-form-item label="验证码" prop="captcha">
        <el-input
          type="captcha"
          v-model="loginForm.captcha"
          autocomplete="off"
          class="captcha"
          @keydown.native.enter="submitForm('loginForm')"
        ></el-input>
        <span class="captcha-svg" v-html="captchaSvg" @click="refresh"></span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('loginForm')"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import allRoutes from '@/router/allRoutes'
import recursionRoutes from '@/utils/recursionRoutes'
import { getCaptcha, verifyCaptcha, login, getMenuList } from '@/api'
/*
登录逻辑的实现
1、收集用户输入的username&password 传递给后端
2、登录通过后，将后端返回的token存到本地，跳转页面
3、每次请求的时候，携带token到请求头authorization
4、展示token 校验正确的数据
5、校验不通过，跳转到登录页面
*/
export default {
  data() {
    // 校验用户名
    var validateUsername = (rule, value, callback) => {
      //  console.log(rule); //一个函数
      //  console.log(value);//输入的值
      // 用户名正则，4到16位（字母，数字，下划线，减号）
      let regExp = /^[a-zA-Z0-9_-]{3,16}$/
      if (regExp.test(value)) {
        callback()
      } else {
        callback('用户名必须：4到16位（字母，数字，下划线，减号）')
      }
    }
    var validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback('请输入密码')
      } else {
        callback()
      }
    }
    var validateCaptcha = (rule, value, callback) => {
      if (value === '' || value.length !== 5) {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    return {
      captchaSvg: '', //从服务器获取下来的验证码svg结构
      loginForm: {
        username: '',
        password: '',
        captcha: '',
      },
      rules: {
        username: [{ validator: validateUsername, trigger: 'blur' }],
        password: [{ validator: validatePassword, trigger: 'blur' }],
        captcha: [{ validator: validateCaptcha, trigger: 'blur' }],
      },
    }
  },
  mounted() {
    this.getCaptchaCode()
  },
  methods: {
    // 刷新验证码
    refresh() {
      this.getCaptchaCode()
    },
    // 封装一个方法获取验证码
    getCaptchaCode() {
      // 调用http方法
      getCaptcha().then((res) => {
        // console.log(res);
        this.captchaSvg = res.data.img
      })
    },
    submitForm(formName) {
      console.log(11)
      this.$refs[formName].validate((valid) => {
        // console.log(this.$refs[formName]);
        //调用一个方法：validate()
        if (valid) {
          // 加载动画
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          //本地表单校验通过
          // 点击提交按钮之后先校验验证码
          verifyCaptcha(this.loginForm.captcha).then((res) => {
            // console.log(res); day校验的验证码是否正确
            if (res.data.state) {
              // 正确=》校验用户名密码
              let { username, password } = this.loginForm
              login(username, password).then((res) => {
                loading.close()
                if (res.data.state) {
                  // 用户名和密码正确
                  let { permission, token, userInfo } = res.data
                  // 将token 储存到本地
                  localStorage.setItem('yf-token', token)

                  // 登录成功获取用户的菜单
                  /*
                  将接口的数据请求回来，这种带childern的是树形结构
                  通过这个数据生成菜单，
                  */

                  // 页面刷新时获取验证码
                  this.getCaptchaCode()
                  // 跳转到首页
                  this.$store.dispatch('FETCH_MENULIST').then(() => {
                    // console.log(1111)
                  })
                  this.$router.push('/')
                } else {
                  this.$message.error('用户名或密码错误')
                }
              })
            } else {
              // 错误 =》提示验证码错误
              this.getCaptchaCode()
              this.$message.error('验证码错误')
              loading.close()
            }
          })
        } else {
          console.log('error submit!!')
          loading.close()
          return false
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.captcha {
  vertical-align: top;
  margin-right: 10px;
}
.captcha-svg {
  background: #fff;
  display: inline-block;
  height: 42px;
  width: 140px;
  text-align: center;
  cursor: pointer;
  border: 0;
  border-radius: 5px;
}

.login__container {
  position: relative;
}
.login__container {
  ::v-deep .el-input__inner {
    margin-right: 10px;
    width: 200px;
  }
  ::v-deep .captchaInput {
    width: 100px;
  }
  ::v-deep .bg_video {
    position: fixed;
    right: 0;
    bottom: 0;
    z-index: -1;
  }
  ::v-deep .el-form {
    width: 400px;
    height: 400px;
    position: absolute;
    top: 500px;
    bottom: 0;
    right: 0;
    left: 0;
    margin: auto;
    background-color: rgba(3, 3, 3, 0.2);
    display: flex;
    justify-content: center;
    flex-direction: column;
    color: #fff;
  }
  ::v-deep .el-form-item__label {
    color: #fff;
  }
  ::v-deep h1 {
    text-align: center;
    margin-bottom: 20px;
  }
  ::v-deep .el-button--primary {
    width: 200px;
    background: linear-gradient(90deg, #1596fb, #002dff);
  }
  ::v-deep .el-form-item__content {
    position: relative;
  }
}
</style>
